#! /Users/heJing/.pyenv/versions/3.8.10/envs/PMShop/bin/python

# 0，设置脚本导包路径
import sys
sys.path.insert(0,'../') # 让该脚本回到上一级，和PMSP就同级了

# 1,加载系统环境配置
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'PMSP.settings.dev')

# 2,django.setup,保证所有的类，都可以使用
import django
django.setup()

# 3，导入生成页面需要的类
from goods.models import SKU
from PMSP.utils.my_category import get_category
from django.shortcuts import loader
from django.conf import settings

# 4，生成详情页的函数
def generate_static_sku_detail_html(sku_id):
    categories = get_category()
    sku = SKU.objects.get(id=sku_id)
    # 构建当前商品的规格键
    sku_specs = sku.specs.order_by('spec_id')
    sku_key = []
    for spec in sku_specs:
        sku_key.append(spec.option.id)
    # 获取当前商品的所有SKU
    skus = sku.spu.sku_set.all()
    # 构建不同规格参数（选项）的sku字典
    spec_sku_map = {}
    for s in skus:
        # 获取sku的规格参数
        s_specs = s.specs.order_by('spec_id')
        # 用于形成规格参数-sku字典的键
        key = []
        for spec in s_specs:
            key.append(spec.option.id)
        # 向规格参数-sku字典添加记录
        spec_sku_map[tuple(key)] = s.id
    # 获取当前商品的规格信息
    goods_specs = sku.spu.specs.order_by('id')
    # 若当前sku的规格信息不完整，则不再继续
    if len(sku_key) < len(goods_specs):
        return
    for index, spec in enumerate(goods_specs):
        # 复制当前sku的规格键
        key = sku_key[:]
        # 该规格的选项
        spec_options = spec.options.all()
        for option in spec_options:
            # 在规格参数sku字典中查找符合当前规格的sku
            key[index] = option.id
            option.sku_id = spec_sku_map.get(tuple(key))
        spec.spec_options = spec_options

    context = {
        "sku": sku,
        "categories": categories,
        "category": sku.category,
        'specs': goods_specs,
    }

    # 渲染页面
    template = loader.get_template("detail.html")
    html_text = template.render(context)
    file_path = os.path.join(settings.STATICFILES_DIRS[0],f'detail/{sku_id}.html')
    with open(file_path,'w',encoding='utf-8') as f:
        f.write(html_text)

# 5，调用详情页函数
if __name__ == '__main__':
    # 查询所有的skus
    skus = SKU.objects.all()

    # 给所有的skus都生成一个静态页面
    for sku in skus:
        print(f"sku_id = {sku.id}")
        generate_static_sku_detail_html(sku_id=sku.id)
